package kubernetes

import (
	"errors"
	"fmt"
	"k8s-admin/global"
	"k8s-admin/utils"
	"os"

	"gopkg.in/yaml.v2"
	appsv1 "k8s.io/api/apps/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/json"
)

type DeploymentList struct {
	Items []appsv1.Deployment
	Total int `json:"total"`
}

func (d *k8sCluster) GetClusterDeploymentList(cid, Namespace string) (*DeploymentList, error) {
	ctx, cancel, cache, err := utils.ClusterClient(cid)
	defer cancel()
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return nil, err
	}
	list, err := cache.AppsV1().Deployments(Namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, err
	} else {
		return &DeploymentList{
			Items: list.Items,
			Total: len(list.Items),
		}, nil

	}
}

func (d *k8sCluster) DeleteClusterDeployment(cid, Namespace, DeploymentName string) error {

	ctx, cancel, cache, err := utils.ClusterClient(cid)
	defer cancel()
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return err

	}
	err = cache.AppsV1().Deployments(Namespace).Delete(ctx, DeploymentName, metav1.DeleteOptions{})
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (d *k8sCluster) UpdateClusterDeployment(cid, Namespace, DeploymentData string) error {

	ctx, cancel, cache, err := utils.ClusterClient(cid)
	defer cancel()
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return err

	}
	// 创建包含 apps/v1 版本的 Deployment 的 Scheme
	dest, err := utils.DecodeBase64(DeploymentData)
	if err != nil {
		return err
	} else {
		deployment := &appsv1.Deployment{}

		err := json.Unmarshal([]byte(dest), deployment)
		if err != nil {
			return err
		}
		_, err = cache.AppsV1().Deployments(Namespace).Update(ctx, deployment, metav1.UpdateOptions{})
		if err != nil {
			global.TPLogger.Error(err.Error())
			return errors.New("Deployment资源更新失败")
		} else {
			return nil
		}
	}
}
func (d *k8sCluster) CreateClusterDeployment(cid, Namespace, DeploymentData string) error {

	// 将前端传送过来的json数据进行解析
	ctx, cancel, cache, err := utils.ClusterClient(cid)
	defer cancel()
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return err

	}
	dest, err := utils.DecodeBase64(DeploymentData)
	if err != nil {
		return err
	} else {
		deployment := &appsv1.Deployment{}

		err := json.Unmarshal([]byte(dest), deployment)
		if err != nil {
			return err
		}
		_, err = cache.AppsV1().Deployments(Namespace).Create(ctx, deployment, metav1.CreateOptions{})
		if err != nil {
			global.TPLogger.Error("创建deployment失败:", err.Error())

			return err

		} else {
			return nil
		}
	}

}

func (d *k8sCluster) GetClusterDeployment(cid string, Namespace string, DeploymentName string) (*appsv1.Deployment, error) {
	ctx, cancel, cache, err := utils.ClusterClient(cid)
	defer cancel()
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return nil, err
	}
	get, err := cache.AppsV1().Deployments(Namespace).Get(ctx, DeploymentName, metav1.GetOptions{})
	if err != nil {
		return nil, err
	} else {
		return get, err
	}

}

/*通过yaml文件上传方式创建Deployment资源*/
func (d *k8sCluster) CreateClusterDeploymentFile(cid, Namespace string, DeploymentData string) error {
	file, err := os.ReadFile(DeploymentData)
	if err != nil {
		global.TPLogger.Error(fmt.Sprintln("读取上传yaml文件内容失败：", err.Error()))
		return err
	} else {
		ctx, cancel, cache, err := utils.ClusterClient(cid)
		defer cancel()
		if err != nil {
			global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
			return err
		}

		deployment := &appsv1.Deployment{}
		err = yaml.Unmarshal(file, deployment)
		if err != nil {
			global.TPLogger.Error("yaml内容解析失败:", err.Error())
			return errors.New("yaml内容解析失败")
		} else {
			_, err = cache.AppsV1().Deployments(Namespace).Create(ctx, deployment, metav1.CreateOptions{})
			if err != nil {
				global.TPLogger.Error("创建deployment失败:", err.Error())
				return err
			} else {
				err := os.RemoveAll(DeploymentData)
				if err != nil {
					global.TPLogger.Error("yaml文件删除失败:", err.Error())
				}
				return nil
			}
		}

	}
}

// 图形创建Deployment
func (d *k8sCluster) CreateClusterDeploymentUI(cid, Namespace string, DeploymentData string) error {
	ctx, cancel, cache, err := utils.ClusterClient(cid)
	defer cancel()
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return err
	}
	// base64解码
	deply, err := utils.DecodeBase64(DeploymentData)
	if err != nil {
		global.TPLogger.Error("base64解码失败:", err.Error())

		return errors.New("base64解码失败")
	} else {
		deployment := &appsv1.Deployment{}
		err = json.Unmarshal([]byte(deply), deployment)
		if err != nil {
			global.TPLogger.Error("json内容解析失败:", err.Error())
			return errors.New("json内容解析失败")
		} else {
			_, err = cache.AppsV1().Deployments(Namespace).Create(ctx, deployment, metav1.CreateOptions{})
			if err != nil {
				global.TPLogger.Error("创建deployment失败:", err.Error())
				return err
			} else {
				return nil
			}
		}
	}

}
